package com.gears_software.bbnetwork.activitys;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.WindowFeature;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.avos.avoscloud.AVAnalytics;
import com.gears_software.bbnetwork.R;
import com.gears_software.bbnetwork.adapters.RecordAdapter;
import com.gears_software.bbnetwork.datas.finders.IBBNetworkFinder;
import com.gears_software.bbnetwork.datas.finders.impl.IBBNetworkFinderImpl;
import com.gears_software.bbnetwork.datas.models.ReportInfoModel;
import com.gears_software.bbnetwork.datas.models.ResultModel;
import com.gears_software.bbnetwork.datas.models.ReturnCode;
import com.gears_software.bbnetwork.utlis.BBNetworkSharedPref_;
import com.gears_software.bbnetwork.utlis.CommonUtils;
import com.gears_software.bbnetwork.utlis.ToastUI;
import com.gears_software.common.utils.SwipeRefreshLoadListView.view.XListView;
import com.gears_software.common.utils.SwipeRefreshLoadListView.view.XListView.IXListViewListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.weixin.controller.UMWXHandler;

/**
 * 报单列表
 * 
 * @author DY-PC
 * 
 */
@EActivity(R.layout.activity_baodanrecord)
@WindowFeature(Window.FEATURE_NO_TITLE)
public class BaoDanListActivity extends Activity {

	@ViewById
	XListView listview_baodan;

	@Pref
	BBNetworkSharedPref_ sp;

	@Bean(IBBNetworkFinderImpl.class)
	IBBNetworkFinder finder;

	List<ReportInfoModel> list = new ArrayList<ReportInfoModel>();

	String userid;

	RecordAdapter adapter;

	Date currentDate;

	PopupWindow window;

	@Bean
	ToastUI toast;

	UMSocialService mController;
	UMQQSsoHandler qqSsoHandler;
	UMWXHandler wxCircleHandler;
	UMWXHandler wxHandler;
	Integer pageNum = 1;//第几页

	@AfterViews
	void onCreate() {
		initWindow();
		userid = sp.userId().get();
		CommonUtils.showDialog(this);
		listview_baodan.setPullLoadEnable(true);
		listview_baodan.setPullRefreshEnable(false);
		listview_baodan.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
			}

			@Override
			public void onLoadMore() {
				loadData();
			}
		});
		getList();

		// 首先在您的Activity中添加如下成员变量
		mController = UMServiceFactory.getUMSocialService("com.umeng.share");
		// 设置分享内容
		mController.setShareContent("http://www.bibefc.com/mobile/share.html");

		InputStream input = getResources()
				.openRawResource(R.drawable.name_logo);
		Bitmap bitmap = BitmapFactory.decodeStream(input);
		// 设置分享图片, 参数2为图片的url地址
		mController.setShareMedia(new UMImage(this, bitmap));

		String appID = "wx726a273d06a8ebf0";
		String appSecret = "5e8de194084ce5195c95247fabacd188";
		// 添加微信平台
		 wxHandler = new UMWXHandler(this, appID, appSecret);
		wxHandler.addToSocialSDK();

		// 添加微信朋友圈
		wxCircleHandler = new UMWXHandler(this, appID, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();

		// 参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
		qqSsoHandler = new UMQQSsoHandler(this, "1104759317",
				"awAYUqcXhajIW4K7");
		qqSsoHandler.addToSocialSDK();

	}

	// 分享按钮
	@Click
	void txt_share() {
		window.showAtLocation(new View(this), Gravity.BOTTOM, 0, 0);
	}

	private void initWindow() {
		View view = getLayoutInflater().from(this).inflate(
				R.layout.window_share, null);
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				window.dismiss();
			}
		});
		RelativeLayout layout_pengyouquan = (RelativeLayout) view
				.findViewById(R.id.layout_pengyouquan);
		RelativeLayout relative_weixin = (RelativeLayout) view
				.findViewById(R.id.relative_weixin);
		RelativeLayout layout_QQ = (RelativeLayout) view
				.findViewById(R.id.layout_QQ);
		RelativeLayout relative_sms = (RelativeLayout) view
				.findViewById(R.id.relative_sms);
		// 朋友圈分享
		layout_pengyouquan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				shareFriend();
			}
		});
		// 微信分享
		relative_weixin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				weixinFriend();
			}
		});
		// qq分享
		layout_QQ.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				shareQQ();
			}
		});
		// 短信分享
		relative_sms.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(Intent.ACTION_SENDTO);
				intent.setData(Uri.parse("smsto:"));
				intent.putExtra("sms_body",
						"比比投标保函，安全，便捷，高效；在线办理：http://www.bibefc.com；客服电话：4000000388");
				startActivity(intent);
			}
		});

		window = new PopupWindow(view, LayoutParams.MATCH_PARENT, 410);
		window.setAnimationStyle(android.R.style.Animation_InputMethod);
		window.setBackgroundDrawable(new ColorDrawable(0));
		window.setOutsideTouchable(true);
		window.setFocusable(true);
	}

	@Background
	void getList() {
		ResultModel<List<ReportInfoModel>> res = finder.getBaodanList(userid,
				pageNum.toString());
		if (res.getReturnCode().equals(ReturnCode.SUCCEED)) {
			setList(res.getResObj());
		} else {
			showTxt(res.getMessage());
		}
		closeDialog();
	}

	@Background
	void loadData() {
		ResultModel<List<ReportInfoModel>> res = finder.getBaodanList(userid,
				pageNum.toString());
		if (res.getReturnCode().equals(ReturnCode.SUCCEED)) {
			if (res.getResObj() != null && res.getResObj().size() > 0) {
				addData(res.getResObj());
			} else {
				showTxt("没有更多数据了！");
				closeLoadListview();
			}
		} else {
			showTxt(res.getMessage());
			closeLoadListview();
		}
	}

	@UiThread
	void addData(List<ReportInfoModel> data) {
		list.addAll(data);
		adapter.notifyDataSetChanged();
		listview_baodan.stopLoadMore();
		pageNum++;
	}

	@UiThread
	void closeLoadListview() {
		listview_baodan.stopLoadMore();
		listview_baodan.setPullLoadEnable(false);
	}

	// 减去时间
	private String getDate(Date time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(time);
		gc.add(2, -3);
		currentDate = gc.getTime();
		return sdf.format(gc.getTime());
	}

	@UiThread
	void closeDialog() {
		CommonUtils.closeDialog();
	}

	@UiThread
	void setList(List<ReportInfoModel> list) {
		this.list.clear();
		this.list.addAll(list);
		adapter = new RecordAdapter(this, this.list);
		listview_baodan.setAdapter(adapter);
		pageNum++;
	}

	@UiThread
	void showTxt(String txt) {
		toast.ShowToast(txt);
	}

	@Click
	void image_back() {
		finish();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		AVAnalytics.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AVAnalytics.onPause(this);
	}

	private void weixinFriend() {
		wxHandler.setTitle("比翼联盟分享");
		wxHandler.setTargetUrl("http://www.bibefc.com/mobile/share.html");
		mController.postShare(this, SHARE_MEDIA.WEIXIN, new SnsPostListener() {

			@Override
			public void onStart() {
				// toast.ShowToast("开始分享");

			}

			@Override
			public void onComplete(SHARE_MEDIA arg0, int arg1,
					SocializeEntity arg2) {
				if (arg1 == 200) {
					toast.ShowToast("分享成功！");
				} else {
					String eMsg = "";
					if (arg1 == -101) {
						eMsg = "没有授权";
					}
					toast.ShowToast("分享失败或已取消[" + arg1 + "]" + eMsg);
				}
			}
		});
	}

	// 朋友圈分享
	private void shareFriend() {
		wxCircleHandler.setTitle("比翼联盟分享");
		wxCircleHandler.setTargetUrl("http://www.bibefc.com/mobile/share.html");
		mController.postShare(this, SHARE_MEDIA.WEIXIN_CIRCLE,
				new SnsPostListener() {

					@Override
					public void onStart() {
						// toast.ShowToast("开始分享");

					}

					@Override
					public void onComplete(SHARE_MEDIA arg0, int arg1,
							SocializeEntity arg2) {
						if (arg1 == 200) {
							toast.ShowToast("分享成功！");
						} else {
							String eMsg = "";
							if (arg1 == -101) {
								eMsg = "没有授权";
							}
							toast.ShowToast("分享失败或已取消[" + arg1 + "]" + eMsg);
						}
					}
				});
	}

	private void shareQQ() {
		boolean isqq = CommonUtils.isApkInstalled(this, "com.tencent.mobileqq");
		if (!isqq) {
			showTxt("您还没有装QQ软件");
			return;
		} 
		qqSsoHandler.setTitle("比翼联盟分享");
		qqSsoHandler.setTargetUrl("http://www.bibefc.com/mobile/share.html");
		mController.postShare(this, SHARE_MEDIA.QQ, new SnsPostListener() {

			@Override
			public void onStart() {
				// toast.ShowToast("开始分享");
			}

			@Override
			public void onComplete(SHARE_MEDIA arg0, int arg1,
					SocializeEntity arg2) {
				if (arg1 == 200) {
//					toast.ShowToast("分享成功！");
				} else {
					String eMsg = "";
					if (arg1 == -101) {
						eMsg = "没有授权";
					}
					toast.ShowToast("分享失败或已取消[" + arg1 + "]" + eMsg);
				}
			}
		});
	}
}
